package com.axapoint.opoc.core.dao;

import java.util.ArrayList;

import org.joda.time.DateTime;
import org.joda.time.Interval;

import com.axapoint.opoc.core.UserException;

public class UnitRelationTypeFacade extends AbstractFacade<UnitRelationType, UnitRelationType.Value, UnitRelationType.Bitemporal> {

	public UnitRelationTypeFacade(String systemId, String userId) {
		super(systemId, userId, new UnitRelationType(), new UnitRelationType.Value());
	}
	
	public UnitRelation.Value[] getUnitRelations(String uuid, DateTime at) {
		UnitRelationType urt = getEntity(uuid);
		if (urt == null) throw new UserException("Enhedsrelationstype UUID: " + uuid);
		
		ArrayList<UnitRelation.Value> result = new ArrayList<UnitRelation.Value>();
        for (UnitRelation.Value v : urt.getUnitRelations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		result.add(v);
        	}
        }
		
		return result.toArray(new UnitRelation.Value[0]);
	}

	@Override
	public ObjectRegistration[] getAffectedEntities(String uuid, Interval newInterval) {
		ArrayList<ObjectRegistration> result = new ArrayList<ObjectRegistration>();
		
		UnitRelationType urt = getEntity(uuid);
		
		// Check unitRelations
		for (UnitRelation.Value l : urt.getUnitRelations()) {
			Interval i = l.getEntity().getValues().get(newInterval.getStart()).getValidityInterval();
			
			// If the unit location does not have interval this can contain new location it is affected
			if (!i.contains(newInterval)) {
				result.add(l.getEntity());
			}
		}
		
		return result.toArray(new ObjectRegistration[0]);
	}

}